package com.phiture.erp.finance.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.MPJLambdaWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import com.phiture.erp.basic.api.pojo.resp.ErpAccountResp;
import com.phiture.erp.basic.api.service.ErpAccountApi;
import com.phiture.erp.basic.api.service.ErpSupplierApi;
import com.phiture.erp.common.constants.ErpNoPrefixConstants;
import com.phiture.erp.common.enums.ErpAuditStatus;
import com.phiture.erp.common.utils.ErpNoGenerator;
import com.phiture.erp.finance.core.event.ErpFinancePaymentEvent;
import com.phiture.erp.finance.core.pojo.dto.ErpFinancePaymentEventDTO;
import com.phiture.erp.finance.core.pojo.dto.GenerateErpFinancePaymentDTO;
import com.phiture.erp.finance.core.pojo.vo.payment.ErpFinancePaymentPageReqVO;
import com.phiture.erp.finance.core.pojo.vo.payment.ErpFinancePaymentSaveReqVO;
import com.phiture.erp.finance.core.service.ErpFinancePaymentService;
import com.phiture.erp.finance.core.service.ErpFinanceStatementService;
import com.phiture.erp.finance.dal.entity.ErpFinancePaymentDO;
import com.phiture.erp.finance.dal.entity.ErpFinancePaymentItemDO;
import com.phiture.erp.finance.dal.entity.ErpFinanceStatementDO;
import com.phiture.erp.finance.dal.mapper.ErpFinancePaymentItemMapper;
import com.phiture.erp.finance.dal.mapper.ErpFinancePaymentMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
import static com.phiture.erp.common.constants.ErrorCodeConstants.*;

// TODO 芋艿：记录操作日志

/**
 * ERP 付款单 Service 实现类
 *
 * @author 芋道源码
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class ErpFinancePaymentServiceImpl implements ErpFinancePaymentService {
    private final ErpFinancePaymentMapper financePaymentMapper;
    private final ErpFinancePaymentItemMapper financePaymentItemMapper;
    private final ErpNoGenerator erpNoGenerator;
    private final ErpFinanceStatementService financeStatementService;
    private final TransactionTemplate transactionTemplate;
    private final ErpSupplierApi supplierApi;
    private final ErpAccountApi accountApi;
    private final AdminUserApi adminUserApi;
    private final ApplicationEventPublisher eventPublisher;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createFinancePayment(ErpFinancePaymentSaveReqVO createReqVO) {
        // 1.1 校验订单项的有效性
        List<ErpFinancePaymentItemDO> paymentItems = validateFinancePaymentItems(
                createReqVO.getSupplierId(), createReqVO.getItems());
        // 1.2 校验供应商
        supplierApi.validateSupplier(createReqVO.getSupplierId());
        // 1.3 校验结算账户
        if (createReqVO.getAccountId() != null) {
            accountApi.validateAccount(createReqVO.getAccountId());
        }
        // 1.4 校验财务人员
        if (createReqVO.getFinanceUserId() != null) {
            adminUserApi.validateUser(createReqVO.getFinanceUserId());
        }
        // 1.5 生成付款单号，并校验唯一性
        String no = getFinancePaymentNo();
        if (financePaymentMapper.selectByNo(no) != null) {
            throw exception(FINANCE_PAYMENT_NO_EXISTS);
        }

        // 2.1 插入付款单
        ErpFinancePaymentDO payment = BeanUtils.toBean(createReqVO, ErpFinancePaymentDO.class, in -> in
                .setNo(no).setStatus(ErpAuditStatus.PROCESS.getStatus()));
        calculateTotalPrice(payment, paymentItems);
        financePaymentMapper.insert(payment);
        // 2.2 插入付款单项
        paymentItems.forEach(o -> o.setPaymentId(payment.getId()));
        financePaymentItemMapper.insertBatch(paymentItems);

        // 3. 更新采购入库、退货的付款金额情况
//        updatePurchasePrice(paymentItems);
        return payment.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFinancePayment(ErpFinancePaymentSaveReqVO updateReqVO) {
        // 1.1 校验存在
        ErpFinancePaymentDO payment = validateFinancePaymentExists(updateReqVO.getId());
        if (ErpAuditStatus.APPROVE.getStatus().equals(payment.getStatus())) {
            throw exception(FINANCE_PAYMENT_UPDATE_FAIL_APPROVE, payment.getNo());
        }
        // 1.2 校验供应商
        supplierApi.validateSupplier(updateReqVO.getSupplierId());
        // 1.3 校验结算账户
        if (updateReqVO.getAccountId() != null) {
            accountApi.validateAccount(updateReqVO.getAccountId());
        }
        // 1.4 校验财务人员
        if (updateReqVO.getFinanceUserId() != null) {
            adminUserApi.validateUser(updateReqVO.getFinanceUserId());
        }
        // 1.5 校验付款单项的有效性
        List<ErpFinancePaymentItemDO> paymentItems = validateFinancePaymentItems(
                updateReqVO.getSupplierId(), updateReqVO.getItems());

        // 2.1 更新付款单
        ErpFinancePaymentDO updateObj = BeanUtils.toBean(updateReqVO, ErpFinancePaymentDO.class);
        calculateTotalPrice(updateObj, paymentItems);
        financePaymentMapper.updateById(updateObj);
        // 2.2 更新付款单项
        updateFinancePaymentItemList(updateReqVO.getId(), paymentItems);
    }

    private void calculateTotalPrice(ErpFinancePaymentDO payment, List<ErpFinancePaymentItemDO> paymentItems) {
        payment.setTotalPrice(getSumValue(paymentItems, ErpFinancePaymentItemDO::getTotalPrice, BigDecimal::add, BigDecimal.ZERO));
        payment.setPaymentPrice(getSumValue(paymentItems, ErpFinancePaymentItemDO::getPaymentPrice, BigDecimal::add, BigDecimal.ZERO));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFinancePaymentStatus(Long id, Integer status) {
        boolean approve = ErpAuditStatus.APPROVE.getStatus().equals(status);
        // 1.1 校验存在
        ErpFinancePaymentDO payment = validateFinancePaymentExists(id);
        // 1.2 校验状态
        if (payment.getStatus().equals(status)) {
            throw exception(approve ? FINANCE_PAYMENT_APPROVE_FAIL : FINANCE_PAYMENT_PROCESS_FAIL);
        }

        // 2. 更新状态
        int updateCount = financePaymentMapper.updateByIdAndStatus(id, payment.getStatus(),
                new ErpFinancePaymentDO().setStatus(status));
        if (updateCount == 0) {
            throw exception(approve ? FINANCE_PAYMENT_APPROVE_FAIL : FINANCE_PAYMENT_PROCESS_FAIL);
        }

        eventPublisher.publishEvent(new ErpFinancePaymentEvent(this, ErpFinancePaymentEventDTO.of(id, status)));
    }

    private List<ErpFinancePaymentItemDO> validateFinancePaymentItems(
            Long supplierId,
            List<ErpFinancePaymentSaveReqVO.Item> list) {
        return convertList(list, o -> BeanUtils.toBean(o, ErpFinancePaymentItemDO.class));
    }

    private void updateFinancePaymentItemList(Long id, List<ErpFinancePaymentItemDO> newList) {
        // 第一步，对比新老数据，获得添加、修改、删除的列表
        List<ErpFinancePaymentItemDO> oldList = financePaymentItemMapper.selectListByPaymentId(id);
        List<List<ErpFinancePaymentItemDO>> diffList = diffList(oldList, newList, // id 不同，就认为是不同的记录
                (oldVal, newVal) -> oldVal.getId().equals(newVal.getId()));

        // 第二步，批量添加、修改、删除
        if (CollUtil.isNotEmpty(diffList.get(0))) {
            diffList.get(0).forEach(o -> o.setPaymentId(id));
            financePaymentItemMapper.insertBatch(diffList.get(0));
        }
        if (CollUtil.isNotEmpty(diffList.get(1))) {
            financePaymentItemMapper.updateBatch(diffList.get(1));
        }
        if (CollUtil.isNotEmpty(diffList.get(2))) {
            financePaymentItemMapper.deleteBatchIds(convertList(diffList.get(2), ErpFinancePaymentItemDO::getId));
        }

        // 第三步，更新采购入库、退货的付款金额情况
//        updatePurchasePrice(CollectionUtils.newArrayList(diffList));
    }

//    private void updatePurchasePrice(List<ErpFinancePaymentItemDO> paymentItems) {
//        paymentItems.forEach(paymentItem -> {
//            BigDecimal totalPaymentPrice = financePaymentItemMapper.selectPaymentPriceSumByBizIdAndBizType(
//                    paymentItem.getBizId(), paymentItem.getBizType());
//            if (ErpBizTypeEnum.PURCHASE_IN.getType().equals(paymentItem.getBizType())) {
//                purchaseInService.updatePurchaseInPaymentPrice(paymentItem.getBizId(), totalPaymentPrice);
//            } else if (ErpBizTypeEnum.PURCHASE_RETURN.getType().equals(paymentItem.getBizType())) {
//                purchaseReturnService.updatePurchaseReturnRefundPrice(paymentItem.getBizId(), totalPaymentPrice.negate());
//            } else {
//                throw new IllegalArgumentException("业务类型不正确：" + paymentItem.getBizType());
//            }
//        });
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFinancePayment(List<Long> ids) {
        // 1. 校验不处于已审批
        List<ErpFinancePaymentDO> payments = financePaymentMapper.selectBatchIds(ids);
        if (CollUtil.isEmpty(payments)) {
            return;
        }
        payments.forEach(payment -> {
            if (ErpAuditStatus.APPROVE.getStatus().equals(payment.getStatus())) {
                throw exception(FINANCE_PAYMENT_DELETE_FAIL_APPROVE, payment.getNo());
            }
        });

        // 2. 遍历删除，并记录操作日志
        payments.forEach(payment -> {
            // 2.1 删除付款单
            financePaymentMapper.deleteById(payment.getId());
            // 2.2 删除付款单项
            List<ErpFinancePaymentItemDO> paymentItems = financePaymentItemMapper.selectListByPaymentId(payment.getId());
            financePaymentItemMapper.deleteBatchIds(convertSet(paymentItems, ErpFinancePaymentItemDO::getId));

            // 2.3 更新采购入库、退货的付款金额情况
//            updatePurchasePrice(paymentItems);
        });
    }

    private ErpFinancePaymentDO validateFinancePaymentExists(Long id) {
        ErpFinancePaymentDO payment = financePaymentMapper.selectById(id);
        if (payment == null) {
            throw exception(FINANCE_PAYMENT_NOT_EXISTS);
        }
        return payment;
    }

    @Override
    public ErpFinancePaymentDO getFinancePayment(Long id) {
        return financePaymentMapper.selectById(id);
    }

    @Override
    public PageResult<ErpFinancePaymentDO> getFinancePaymentPage(ErpFinancePaymentPageReqVO reqVO) {

            MPJLambdaWrapperX<ErpFinancePaymentDO> query = new MPJLambdaWrapperX<ErpFinancePaymentDO>()
                    .likeIfPresent(ErpFinancePaymentDO::getNo, reqVO.getNo())
                    .betweenIfPresent(ErpFinancePaymentDO::getPaymentTime, reqVO.getPaymentTime())
                    .eqIfPresent(ErpFinancePaymentDO::getSupplierId, reqVO.getSupplierId())
                    .eqIfPresent(ErpFinancePaymentDO::getCreator, reqVO.getCreator())
                    .eqIfPresent(ErpFinancePaymentDO::getFinanceUserId, reqVO.getFinanceUserId())
                    .eqIfPresent(ErpFinancePaymentDO::getAccountId, reqVO.getAccountId())
                    .eqIfPresent(ErpFinancePaymentDO::getStatus, reqVO.getStatus())
                    .likeIfPresent(ErpFinancePaymentDO::getRemark, reqVO.getRemark())
                    .orderByDesc(ErpFinancePaymentDO::getId);
            if (reqVO.getBizNo() != null) {
                query.leftJoin(ErpFinancePaymentItemDO.class, ErpFinancePaymentItemDO::getPaymentId, ErpFinancePaymentDO::getId)
                        .eq(reqVO.getBizNo() != null, ErpFinancePaymentItemDO::getBizNo, reqVO.getBizNo())
                        .groupBy(ErpFinancePaymentDO::getId); // 避免 1 对多查询，产生相同的 1
            }
            return financePaymentMapper.selectJoinPage(reqVO, ErpFinancePaymentDO.class, query);

    }

    // ==================== 付款单项 ====================

    @Override
    public List<ErpFinancePaymentItemDO> getFinancePaymentItemListByPaymentId(Long paymentId) {
        return financePaymentItemMapper.selectListByPaymentId(paymentId);
    }

    @Override
    public List<ErpFinancePaymentItemDO> getFinancePaymentItemListByPaymentIds(Collection<Long> paymentIds) {
        if (CollUtil.isEmpty(paymentIds)) {
            return Collections.emptyList();
        }
        return financePaymentItemMapper.selectListByPaymentIds(paymentIds);
    }

    @Override
    public void generatePayment(GenerateErpFinancePaymentDTO dto) {
        if(CollUtil.isEmpty(dto.getStatementNos())){
            log.error("[ErpFinancePaymentService.generatePaymentOrder] 付款单生成失败，对账单号为空");
            throw exception(FINANCE_PAYMENT_GENERATE_ERROR);
        }
        List<ErpFinanceStatementDO> financeStatementList = financeStatementService.getListByFinanceStatementNos(new HashSet<>(dto.getStatementNos()));
        if(CollUtil.isEmpty(financeStatementList)){
            log.error("[ErpFinancePaymentService.generatePaymentOrder] 付款单生成失败，对账单不存在，financeStatementNos:{}", JsonUtils.toJsonString(dto.getStatementNos()));
            throw exception(FINANCE_STATEMENT_NOT_EXISTS);
        }

        ErpAccountResp defaultAccount = accountApi.getDefaultAccount();
        Assert.notNull(defaultAccount, "该用户没有默认账户");
        boolean settleTheBill = Boolean.TRUE.equals(dto.getSettleTheBill());
        Map<Long, ErpFinancePaymentDO> financePaymentMap = new HashMap<>(financeStatementList.size());
        financeStatementList.forEach(item ->{
            financePaymentMap.merge(
                    item.getTransactionUserId(),
                    toErpFinancePaymentDO(item.getTransactionUserId(), defaultAccount.getId(), item.getTotalAmount(), item.getBillingPeriod(), settleTheBill),
                    (originalVal, newVal) -> {
                        originalVal.setTotalPrice(originalVal.getTotalPrice().add(newVal.getTotalPrice()));
                        originalVal.setPaymentPrice(originalVal.getPaymentPrice().add(newVal.getPaymentPrice()));
                        return originalVal;
                    }
            );
        });

        List<ErpFinancePaymentDO> saveList = new ArrayList<>(financePaymentMap.values());
        transactionTemplate.execute(action ->{
            Boolean batch = financePaymentMapper.insertBatch(saveList);
            if(batch){
                Map<Long, Long> financePaymentIdMap = saveList.stream().collect(Collectors.toMap(ErpFinancePaymentDO::getSupplierId, ErpFinancePaymentDO::getId));
                List<ErpFinancePaymentItemDO> items = financeStatementList.stream().map(item ->
                        toErpFinancePaymentItemDO(
                                financePaymentIdMap.get(item.getTransactionUserId()),
                                item.getId(),
                                item.getNo(),
                                item.getTotalAmount(),
                                item.getTransactionAmount(),
                                settleTheBill
                        )
                ).collect(Collectors.toList());
                financePaymentItemMapper.insertBatch(items);
            }
            return true;
        });
    }

    private String getFinancePaymentNo(){
        return erpNoGenerator.generate(ErpNoPrefixConstants.FINANCE_PAYMENT_NO_PREFIX);
    }

    private ErpFinancePaymentDO toErpFinancePaymentDO(Long supplierId, Long defaultAccountId, BigDecimal totalPrice, String billingPeriod, boolean settleTheBill){
        ErpFinancePaymentDO paymentDO = new ErpFinancePaymentDO();
        paymentDO.setPaymentTime(LocalDateTime.now());
        paymentDO.setNo(getFinancePaymentNo());
        paymentDO.setStatus(ErpAuditStatus.PROCESS.getStatus());
        paymentDO.setFinanceUserId(SecurityFrameworkUtils.getLoginUserId());
        paymentDO.setSupplierId(supplierId);
        paymentDO.setTotalPrice(totalPrice);
        paymentDO.setAccountId(defaultAccountId);
        paymentDO.setDiscountPrice(BigDecimal.ZERO);
        if(settleTheBill){
            paymentDO.setPaymentPrice(paymentDO.getTotalPrice().subtract(paymentDO.getDiscountPrice()));
        } else {
            paymentDO.setPaymentPrice(BigDecimal.ZERO);
        }
        paymentDO.setBillingPeriod(billingPeriod);
        return paymentDO;
    }

    private ErpFinancePaymentItemDO toErpFinancePaymentItemDO(Long paymentId, Long bizId, String bizNo, BigDecimal totalPrice, BigDecimal paidPrice, boolean settleTheBill){
        ErpFinancePaymentItemDO itemDO = new ErpFinancePaymentItemDO();
        itemDO.setPaymentId(paymentId);
        itemDO.setBizId(bizId);
        itemDO.setBizNo(bizNo);
        itemDO.setTotalPrice(totalPrice);
        itemDO.setPaidPrice(paidPrice);
        if(settleTheBill){
            itemDO.setPaymentPrice(totalPrice.subtract(paidPrice));
        }else {
            itemDO.setPaymentPrice(BigDecimal.ZERO);
        }
        return itemDO;
    }

}